/*
 * bim模型的model层
 */

import { getModelByCode } from '@/services/modelManageService';
// import { getBimMenuTree, getDifference } from '../services/bimServices';
import buildingUtils from '@/utils/arcgis/layer/buildingScenelayer';
import { message } from 'antd';
import layerCreator from '@/utils/arcgis/layer/layer-creator';
import { jsapi, viewUtils } from '@/utils/arcgis';
import { getSingleWbsStatus } from '@/services/bimServices';

let renderTimes = 0; // 初始化渲染不goto

const popupTemplate = {
  title: 'BIM构件属性',
  content: [
    {
      type: 'fields',
      fieldInfos: [
        {
          fieldName: 't构件名称',
          label: '构件名称',
        },
        {
          fieldName: 'WBS编码',
          label: 'WBS编码',
        },
        {
          fieldName: 'CreatedPhase',
          label: '报验信息',
        },
      ],
    },
  ],
};

async function renderPoiPopup(attributes) {
  let params = new URL(document.location).searchParams;
  let projectId = params.get('i');
  let wbsCode = attributes['WBS编码'];
  window.localStorage.setItem("wbsCode",JSON.stringify(wbsCode));
  if (!wbsCode) {
    return `<div class="c-popup">
    <p class="c-popup-p">
      没有wbs编码
    </p>
  </div>`;
  }
  let esriDom = document.querySelector('.esri-popup__main-container') as HTMLElement
  if(esriDom) esriDom.style.display = 'none'
  return '<div></div>'
//   const data = await getSingleWbsStatus(wbsCode);
//   return `<div class="c-popup">
//   <p class="c-popup-p">
//     ${data.wbsName}
//     <span class="c-popup-status">${data.taskStatusDesc}</span>
//   </p>
//   <p class="c-popup-p">
//     wbsCode <span>${wbsCode} </span>
//   </p>
//   <div class="c-popup-footer">
//     <div class="c-popup-address">${data.calculateStatusDesc}</div>
//     <a class='c-popup-link' target="_blank"  href='${data.linkUrl +
//       '?wbsCode=' +
//       wbsCode +
//       '&projectId=' +
//       projectId}'>查看</a>
//   </div>
// </div>`;
}

async function getWbsPopup(feature) {
  const div = document.createElement('div');
  let baseDom = document.querySelector('.base-panel') as HTMLElement
  if(baseDom && baseDom.style.visibility == 'visible'){
    let esriDom = document.querySelector('.esri-popup__main-container') as HTMLElement
      if(esriDom) esriDom.style.display = 'none'
  } 
  div.innerHTML = await renderPoiPopup(feature.graphic.attributes);
  return div;
}

/**
 * 渲染bim 模型
 * @param _bimList 传单个渲染并goto， 传数组只渲染
 * @param goto 无需使用
 */
async function renderBimLayer(_bimList: any, goto: string | boolean = false) {
  if (!Array.isArray(_bimList)) {
    return renderBimLayer([_bimList], 'gotoLyr');
  }
  let _subLayersWithNoWbs: any[] = [];
  const elevationInfo = {
    mode: 'absolute-height',
    offset: 0,
    unit: 'meters',
  };

  let params = new URL(document.location).searchParams;
  let projectId = params.get('i') || '';

  // 312xw11 312xw13 高浪路
  let elevationInfoOffset = {
    '1448902059425873922': 0.5,
    '1448900554127917057': 0.5,
    '1308241434249887746': 1,
  };
  if (projectId || elevationInfoOffset[projectId]) {
    elevationInfo.offset = elevationInfoOffset[projectId];
  }

  const [PopupTemplate] = await jsapi.load(['esri/PopupTemplate']);
  const popupTemplate = new PopupTemplate({
    // outFields: ['*'],
    title: '{name}',
    content: getWbsPopup,
  });
  _bimList.forEach(async (m, i) => {
    if (!m.url) return;
    const lyr = await layerCreator.create({
      type: 'building',
      url: m.url,
      title: m.name,
    });

    lyr.elevationInfo = elevationInfo;
    lyr.popupTemplate = popupTemplate;

    const view = await viewUtils.isViewReady();
    buildingUtils.setFullModel(lyr);
    // if (goto) {
    if (!i && renderTimes) {
      lyr.when(() => {
        view.goTo(lyr.fullExtent);
      });
    }
    renderTimes += 1;

    lyr.when(_lyr => {
      function hideBuildingComponent(subLayer, i) {
        subLayer.popupTemplate = popupTemplate;
        // subLayer.elevationInfo = elevationInfo;
        if (subLayer.type === 'building-component') {
          // 清除绘制的有问题的模型
          if (subLayer.modelName == 'GenericModel') {
            subLayer.definitionExpression = `FamilyType not in ('桥台处伸缩缝剪切','桥台处伸缩缝','桥台处伸缩缝剪切 2')`;
          }
          // 记录 除了指定模型外 没有 WBS编码 字段的模型
          if (['南部通道宜马三场', '宜马项目三场临建'].indexOf(_lyr.title) == -1) {
            subLayer.when(_subLayer => {
              if (!_subLayer.attributeStorageInfo.some(e => e.name === 'WBS编码')) {
                _subLayersWithNoWbs.push(_subLayer);
                // subLayer.visible = false;
              }
            });
          }
        }
      }
      lyr.allSublayers.forEach(hideBuildingComponent);
    });

    view.map.add(lyr);
  });
  return _subLayersWithNoWbs;
}

export default {
  namespace: 'bimmodel',
  state: {
    bimTree: [], //入库的所有bim模型
    bimList: [],
    addedBimList: [], // 已加载的图层的id
    addedBimNameList: [], // 已加载的图层的name
    subLayersWithNoWbs: [], // 没有wbs编码的字段
    currentBimVersion: {
      name: '',
      version: '',
      bimId: '',
      url: '',
    },
    compareState: false, // 判断当前是否在对比状态

    //------------------ 以上为使用的状态

    bimDifference: {
      add: [{ objectid: '', familyType: '' }],
      delete: [{ objectid: '', familyType: '' }],
    }, //同一模型不同版本的差别
    currentBimInfo: {
      objectid: '',
      name: '',
      modelList: [
        {
          name: '',
          version: '',
          bimId: '',
        },
      ],
    },

    currentBimAttrbutes: [],
    currentBimRenderers: [], // 记录当前Bim模型的renderer
    contrastBimVersion: {
      version: '',
      name: '',
      bimId: '',
    },
    drawingVisible: false, // 图纸底部显示隐藏
    footTableDataSource: [],
  },
  subscriptions: {},

  effects: {
    // 初始化所有模型
    *initAllBimModels({ payload }, { call, put, select }) {
      const { skipFirstRender } = payload;
      try {
        const code = yield select(store => store.app.curProjId);
        if (!code) return;

        // const resp = yield call(getBimMenuTree, code);
        const resp = yield call(getModelByCode, code);

        // todo;
        const cimTrafficBimData = resp.data.modelList.reduce((r, e) => {
          e.bimId = e.objectId;
          r.push(e);
          return r;
        }, []);

        if (cimTrafficBimData.length > 0) {
          // 设置默认模型 给模型树使用
          const { name, bimId, url, version } = cimTrafficBimData[0];
          let subLayersWithNoWbs = [];
          let payload: any = {
            bimList: cimTrafficBimData,
            bimTree: resp.data.data,
            currentBimVersion: { name, bimId, url, version },
          };
          if (!skipFirstRender) {
            const addedBimList: any[] = [];
            cimTrafficBimData.forEach(item => {
              if (
                item.visible &&
                item.name !== 'S11标道路' &&
                item.name !== 'S12标道路' &&
                item.name !== '高浪路道路模型'
              ) {
                addedBimList.push(item);
              }
            });
            subLayersWithNoWbs = yield renderBimLayer(addedBimList);
            payload = {
              ...payload,
              addedBimList: addedBimList.map(m => m.bimId),
              addedBimNameList: addedBimList.map(m => m.name),
              subLayersWithNoWbs,
            };
          }
          yield put({
            type: 'updateState',
            payload,
          });
        }
      } catch (error) {
        message.error('bim模型初始化失败，请检查网络');
      }
    },

    /**toggle 切换建筑显隐 */
    *toggleBimLayer({ payload }, { put, select, call }) {
      const bimList = yield select(store => store.bimmodel.bimList);
      const { addedBimList, addedBimNameList } = yield select(store => store.bimmodel);
      const { id, active } = payload;
      const [model] = bimList.filter(b => b.bimId === id);

      const indexOfId = addedBimList.indexOf(id);

      if (!model) return;
      if (active && indexOfId === -1) {
        yield call(renderBimLayer, model);

        yield put({
          type: 'updateState',
          payload: {
            addedBimList: [...addedBimList, id],
            addedBimNameList: [...addedBimNameList, model.name],
            currentBimVersion: {
              name: model.name,
              version: model.version,
              bimId: model.bimId,
              url: model.url,
            },
          },
        });
      } else if (!active && indexOfId !== -1) {
        yield put({
          type: 'updateState',
          payload: {
            addedBimList: [
              ...addedBimList.slice(0, indexOfId),
              ...addedBimList.slice(indexOfId + 1),
            ],
            addedBimNameList: [
              ...addedBimNameList.slice(0, indexOfId),
              ...addedBimNameList.slice(indexOfId + 1),
            ],
          },
        });
        const view = yield viewUtils.isViewReady();
        const lyr = view.map.layers.find(l => l.title === model.name);
        lyr && view.map.remove(lyr);
      }
    },

    /**隐藏所有除了目标图层 */
    *hideAllBimLayerExcept({ payload }, { call, put, select }) {
      // const addedBimList = yield select(store => store.bimmodel.addedBimList);
      const bimList = yield select(store => store.bimmodel.bimList);
      const { id } = payload;
      const [model, restLayerNames] = bimList.reduce(
        (r, b) => {
          if (b.bimId == id) {
            r[0] = b;
          } else {
            r[1].push(b.name);
          }
          return r;
        },
        ['targetModel', []],
      );

      const view = yield viewUtils.isViewReady();
      const layers = restLayerNames.map(name => view.map.layers.find(l => l.title == name));
      view.map.removeMany(layers);
      if (model) {
        const { name, bimId, url, version } = model;
        yield put({
          type: 'updateState',
          payload: { currentBimVersion: { name, bimId, url, version } },
        });
      }
    },
  },

  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload };
    },

    // 设置入库的所有bim模型
    setBimMenuTreeData(state, action) {
      return {
        ...state,
        bimTree: action.payload,
        currentBimInfo: action.payload[0],
        currentBimVersion: action.payload[0].modelList[0],
      };
    },

    // 设置同一模型不同版本的差别
    setBimDifference(state, action) {
      return { ...state, bimDifference: action.payload };
    },

    // 设置当前模型的基本信息
    setCurrentBimInfo(state, action) {
      return {
        ...state,
        currentBimInfo: action.payload,
        currentBimVersion: action.payload.modelList[0],
      };
    },

    // 设置当前模型的版本信息
    setCurrentBimVersion(state, action) {
      return { ...state, currentBimVersion: action.payload };
    },

    // 设置对比模型的版本信息
    setContrastBimVersion(state, action) {
      return { ...state, contrastBimVersion: action.payload };
    },
    // 修改当前的三维对比状态
    setCompareState(state, action) {
      return { ...state, compareState: action.payload };
    },
    // 设置当前查询bim模型名称
    setSearchValue(state, action) {
      return { ...state, searchvalue: action.payload };
    },
    // 设置当前查询bim模型图纸显示隐藏
    setDrawingVisible(state, action) {
      return { ...state, drawingVisible: action.payload };
    },
    setFootTableDataSource(state, action) {
      return { ...state, footTableDataSource: action.payload };
    },
    // 设置当前查询bim模型的属性
    setCurrentBimAttrbutes(state, action) {
      return { ...state, currentBimAttrbutes: action.payload };
    },
    // 设置当前查询bim模型的render
    setCurrentBimRenderers(state, action) {
      return { ...state, currentBimRenderers: action.payload };
    },
  },
};
